import Vue from 'vue'
import Vuex from 'vuex'
import { Promise } from 'q';
import { resolve } from 'url';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: {
      name: '萨鲁法尔',
      age: parseInt(localStorage.getItem('age')) || 15,
      address: '杜隆塔尔'
    },
    list: [1, 2, 3, 4, 5, 6, 7, 8],
  },
  getters: {
    getList(state) {
      return state.list.filter( item => {
        return item % 2 == 0
      })
    }
  },
  //不可以异步
  mutations: {
    addAge(state, n=2) {
      state.userInfo.age += n;
      localStorage.setItem('age', state.userInfo.age)
    },
  },
  //可以异步 (通过ajax的都走这里)
  actions: {
    addAge(context) {
      context.commit('addAge')
    },
    asyncMode(context) {
      return new Promise(resolve => {
        setTimeout(() => {
          context.commit('addAge');
          resolve(); 
        }, 500);
      })
    }
  }
})
